<?php
class SmsAction extends CommonAction {
	function _initialize() {
		

	}
	private function common(){
		//$this->_inject_check(1);//调用过滤函数
		$this->_inject_check(0);//调用过滤函数
		$this->_checkUser();
		$this->_Admin_checkUser();//后台权限检测
		$this->_Config_name();//调用参数
		header("Content-Type:text/html; charset=utf-8");
	}
	//================================================二级验证
	public function cody(){
	    $this->common();
		$UrlID  = (int) $_GET['c_id'];
	    if (empty($UrlID)){
            $this->error('二级密码错误1!');
            exit;
        }
        if(!empty($_SESSION['user_pwd2'])){
			$url = __URL__."/codys/Urlsz/$UrlID";
			$this->_boxx($url);
			exit;
		}
		$cody   =  M ('cody');
        $list	=  $cody->where("c_id=$UrlID")->field('c_id')->find();
		if ($list){
			$this->assign('vo',$list);
			$this->display('../Public/cody');
			exit;
		}else{
			$this->error('二级密码错误!');
			exit;
		}
	}
	//====================================二级验证后调转页面
	public function codys(){
		$this->common();
		$Urlsz	= $_POST['Urlsz'];
		if(empty($_SESSION['user_pwd2'])){
			$pass	= $_POST['oldpassword'];
			$fck   =  M ('fck');
		    if (!$fck->autoCheckToken($_POST)){
	            $this->error('页面过期请刷新页面!');
	            exit();
	        }
			if (empty($pass)){
				$this->error('二级密码错误!');
				exit();
			}
			$where =  array();
			$where['id'] = $_SESSION[C('USER_AUTH_KEY')];
			$where['passopen'] = md5($pass);
			$list = $fck->where($where)->field('id')->find();
			if($list == false){
				$this->error('二级密码错误!');
				exit();
			}
			$_SESSION['user_pwd2'] = 1;
		}else{
			$Urlsz = $_GET['Urlsz'];
		}
		switch ($Urlsz){
			case 1;
				$_SESSION['UrlPTPass'] = 'MyssSmsConfig';
				$bUrl = __URL__.'/smsConfig';//短信配置
				$this->_boxx($bUrl);
				break;
			default;
				$this->error('二级密码错误!');
				break;
		}
	}

	public function smsConfig(){
	    $this->common();
		$sms_config = M('Sms');
		$type =  'huyi';
		if($_POST){
		    if(empty($_POST['sid'])){
				$this->error('sid错误!');
			}
			if(empty($_POST['token'])){
				$this->error('token错误!');
			}
			
					
		if(empty($_POST['sms_kg'])){
				$this->error('请选择开关!');
			}
			
			
			$data = array(
				'sms_type' => $type,
				'sms_account' => $_POST['sid'],
				'sms_token' => $_POST['token'],
				'sms_kg' => $_POST['sms_kg'],
				
			);
			$id = $sms_config->where(array('sms_type'=>$type))->field('sid')->find();
			if(empty($id)){
				if($sms_config->add($data)){
					$this->success('',__URL__.'/smsConfig');
				}else{
					$this->error('插入错误');
				}
			}else{
				if($sms_config->where(array('sms_type'=>$type))->save($data)){
					$this->success('',__URL__.'/smsConfig');
				}else{
					$this->error('更新错误');
				}
			}
			exit;
		}
		$rt = $sms_config->where(array('sms_type'=>$type))->find();
		if($rt){
			$this->assign('config',$rt);
		}
		$this->display();
	}
	private function smsSend($to,$datas,$tempId = 99){
		
		$type =  'yuntongxun';
		$sms_config = M('Sms')->where(array('sms_type'=>$type))->find();
		if(!empty($sms_config)){
			//主帐号,对应开官网发者主账号下的 ACCOUNT SID
            $accountSid= $sms_config['sms_account'];
            //主帐号令牌,对应官网开发者主账号下的 AUTH TOKEN
            $accountToken= $sms_config['sms_token'];
            //应用Id，在官网应用列表中点击应用，对应应用详情中的APP ID
            //在开发调试的时候，可以使用官网自动为您分配的测试Demo的APP ID
            $appId= $sms_config['sms_appid'];
            //请求地址
            //沙盒环境（用于应用开发调试）：sandboxapp.cloopen.com
            //生产环境（用户应用上线使用）：app.cloopen.com
            $serverIP='app.cloopen.com';
            //请求端口，生产环境和沙盒环境一致
            $serverPort='8883';
            //REST版本号，在官网文档REST介绍中获得。
            $softVersion='2013-12-26';
			import ( "@.ORG.RestSms" );  //导入sms sdk
			$rest = new REST($serverIP,$serverPort,$softVersion);
            $rest->setAccount($accountSid,$accountToken);
            $rest->setAppId($appId);
            
            // 发送模板短信
            //echo "Sending TemplateSMS to $to <br/>";
			if(!empty($tempId)){
				switch($tempId){
					case 1:
					break;
					default:
					$tempId = $sms_config['sms_tid'];
					break;
				}
			}
		    /* $this->verfiy_report($to,$datas);
			return '发送成功 注意接收';
			 exit; */
            $result = $rest->sendTemplateSMS($to,$datas,$tempId);
            if($result == NULL ) {
			  return "result error!";
              //echo "result error!";
              break;
            }
            if($result->statusCode!=0) {
               //echo "error code :" . $result->statusCode . "<br>";
               //echo "error msg :" . $result->statusMsg . "<br>";
			   $tmp = (array)$result->statusMsg;
			   return array_pop($tmp);
			   //return '发送失败';
               //TODO 添加错误处理逻辑
            }else{
               //echo "Sendind TemplateSMS success!<br/>";
			  // 发送成功记录
			  $this->verfiy_report($to,$datas);
			  // 已md5加密的方式存储短信验证码
			  $_SESSION['mobile_code'] = md5($datas[0]);
              $smsmessage = $result->TemplateSMS;
			  return '发送成功注意接收';
              //echo "dateCreated:".$smsmessage->dateCreated."<br/>";
               //echo "smsMessageSid:".$smsmessage->smsMessageSid."<br/>";
               //TODO 添加成功处理逻辑
            }
		}else{
			return '短信读取配置错误';
		}
		
		
	}
	
	private function random($length = 6 , $numeric = 0) {
	PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
	if($numeric) {
		$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
	} else {
		$hash = '';
		$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
		$max = strlen($chars) - 1;
		for($i = 0; $i < $length; $i++) {
			$hash .= $chars[mt_rand(0, $max)];
		}
	}
	    return $hash;
    }
	
    
    	public function checkmobile1(){
    	
    
	    //echo $_POST['verify'];
		$time_tips = 5;	// 验证码实效时间提醒
		if(empty($_POST['mobile'])) {
			$this->ajaxReturn('','手机号不能为空',0);
		}
		
		// 手机唯一性验证
		$fck = M('fck');
		
		// 验证码发送间隔限制
		$verify_report = M('verify_report');
		$report = $verify_report -> where(array('phone'=>$_POST['mobile']))->find();
		if(!empty($report)){
			// 时间间隔检测
			$cur_time = mktime();
			if(!empty($report['datetime'])){
				if(abs($cur_time - $report['datetime']) < 60){
					$this->ajaxReturn('','请在60秒后再次发送',0);
					exit;
				}
			}
		}
		// 短信模版
		$mobile_code = $this->random(4,1);
		// 发送短信
	$msg = $this->smsSend2($_POST['mobile'],$mobile_code);
	}
	
    
    
    
	public function checkmobile(){
	
	    //echo $_POST['verify'];
		$time_tips = 5;	// 验证码实效时间提醒
		if(empty($_POST['mobile'])) {
			$this->ajaxReturn('','手机号不能为空',0);
		}
	//	elseif (empty($_POST['code'])){
	//		$this->ajaxReturn('','验证码不能为空',0);
	//	}
	//	if($_SESSION['verify'] != md5($_POST['code'])) {
	//		$this->ajaxReturn('','验证码错误',0);
	//	}
		// 手机唯一性验证
		$fck = M('fck');
		$id = $fck->where(array('user_tel'=>$_POST['mobile']))->field('id')->find();
		if($id > 0){
			$this->ajaxReturn('','手机号码已经存在',0);
		}
		// 验证码发送间隔限制
		$verify_report = M('verify_report');
		$report = $verify_report -> where(array('phone'=>$_POST['mobile']))->find();
		if(!empty($report)){
			// 时间间隔检测
			$cur_time = mktime();
			if(!empty($report['datetime'])){
				if(abs($cur_time - $report['datetime']) < 60){
					$this->ajaxReturn('','请在60秒后再次发送',0);
					exit;
				}
			}
		}
		// 短信模版
		$mobile_code = $this->random(4,1);
		
		// 发送短信
		$msg = $this->smsSend2($_POST['mobile'],$mobile_code);
		//$this->ajaxReturn('',$msg,0);
	}
	private function smsSend2($to,$datas){
			$mobile=$to;
			$mobile_code=$datas;
			$target = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
			$post_data = "account=cf_1002&password=110011&mobile=".$mobile."&content=".rawurlencode("您的校验码是：".$mobile_code."请不要把校验码泄露给其他人。");
			//密码可以使用明文密码或使用32位MD5加密
			$gets =$this->xml_to_array($this->Post($post_data, $target));
			if($gets['SubmitResult']['code']==2){
			$_SESSION['mobile'] = $mobile;
		$_SESSION['mobile_code'] = $mobile_code;
			}
			//echo $gets['SubmitResult']['msg'];
		}
		
		
	private function smsSend3($to,$datas){
			$mobile=$to;
			$mobile_code=$datas;
			$target = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
			$post_data = "account=cf_1002&password=110011&mobile=".$mobile."&content=".rawurlencode("您好!".$mobile_code."请注意查收!!!");
			//密码可以使用明文密码或使用32位MD5加密
			$gets =$this->xml_to_array($this->Post($post_data, $target));
			if($gets['SubmitResult']['code']==2){
			$_SESSION['mobile'] = $mobile;
			$_SESSION['mobile_code'.$mobile] = $mobile_code;
			}
			//echo $gets['SubmitResult']['msg'];
		}
			
	function Post($curlPost,$url){
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_NOBODY, true);
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
		$return_str = curl_exec($curl);
		curl_close($curl);
		return $return_str;
	}
	function xml_to_array($xml){
	$reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
		if(preg_match_all($reg, $xml, $matches)){
			$count = count($matches[0]);
			for($i = 0; $i < $count; $i++){
			$subxml= $matches[2][$i];
			$key = $matches[1][$i];
				if(preg_match( $reg, $subxml )){
					$arr[$key] = $this->xml_to_array( $subxml );
				}else{
					$arr[$key] = $subxml;
				}
			}
		}
	return $arr;
	}
	
	
	//匹配提示
public function dengjia($pho){

		$time_tips = 5;	// 验证码实效时间提醒
		
		// 手机唯一性验证
		$fck = M('fck');
		$verify_report = M('verify_report');
		$report = $verify_report -> where(array('phone'=>$pho))->find();
		if(!empty($report)){
			// 时间间隔检测
			$cur_time = mktime();
			if(!empty($report['datetime'])){
				if(abs($cur_time - $report['datetime']) < 60){
					$this->ajaxReturn('','请在60秒后再次发送',0);
					exit;
				}
			}
		}
		// 短信模版
		$mobile_code ='您的订单已匹配成功!!!';
		// 发送短信
		$msg = $this->smsSend3($pho,$mobile_code);
		//$msg = $this->smsSend2($_POST['mobile'],$mobile_code);
	  	//echo $msg;exit;
		//$this->ajaxReturn('',$msg,0);
		
	  // $this->redirect('Index/index');
	}
	
	
	//拒绝打款
public function ckm($pho){

  
		$time_tips = 5;	// 验证码实效时间提醒
		
		// 手机唯一性验证
		$fck = M('fck');
		$verify_report = M('verify_report');
		$report = $verify_report -> where(array('phone'=>$pho))->find();
		if(!empty($report)){
			// 时间间隔检测
			$cur_time = mktime();
			if(!empty($report['datetime'])){
				if(abs($cur_time - $report['datetime']) < 60){
					$this->ajaxReturn('','请在60秒后再次发送',0);
					exit;
				}
			}
		}
		// 短信模版
		$mobile_code ='您匹配成功的上家拒绝打款,该用户账号已被冻结,请联系您的上家向后台申请重新匹配打款!!!';
		// 发送短信
	//	$msg = $this->smsSend2($pho,array($mobile_code));
		//$msg = $this->smsSend2($_POST['mobile'],$mobile_code);
	  	//echo $msg;exit;
		//$this->ajaxReturn('',$msg,0);
		
	  // $this->redirect('Index/index');
	}
	
	
	
	
	
	//确认收款
	
  public function qsh($pk){

  
		$time_tips = 5;	// 验证码实效时间提醒
		
		// 手机唯一性验证
		$fck = M('fck');
		$verify_report = M('verify_report');
		$report = $verify_report -> where(array('phone'=>$pk))->find();
		if(!empty($report)){
			// 时间间隔检测
			$cur_time = mktime();
			if(!empty($report['datetime'])){
				if(abs($cur_time - $report['datetime']) < 60){
					$this->ajaxReturn('','请在60秒后再次发送',0);
					exit;
				}
			}
		}
		// 短信模版
		$mobile_code ='您匹配成功的用户已经确认收款!!!';
		// 发送短信
		$msg = $this->smsSend3($pk,$mobile_code);
	  //	echo $msg; exit;
		//$this->ajaxReturn('',$msg,0);
		
	  // $this->redirect('Index/index');
	}
	
	
	
	
		//确认打款
   public function ckq($ph){

  
		$time_tips = 5;	// 验证码实效时间提醒
		
		// 手机唯一性验证
		$fck = M('fck');
		$verify_report = M('verify_report');
		$report = $verify_report -> where(array('phone'=>$ph))->find();
		if(!empty($report)){
			// 时间间隔检测
			$cur_time = mktime();
			if(!empty($report['datetime'])){
				if(abs($cur_time - $report['datetime']) < 60){
					$this->ajaxReturn('','请在60秒后再次发送',0);
					exit;
				}
			}
		}
		// 短信模版
		$mobile_code ='您已匹配成功的上家已经确认打款,24小时内将会给您打款否则将自动封号!!!';
		// 发送短信
		$msg = $this->smsSend3($ph,$mobile_code);
	  	//echo $msg;exit;
		//$this->ajaxReturn('',$msg,0);
		
	  // $this->redirect('Index/index');
	}
	
	
	
			//延时打款
   public function yanshi2($ys){

  
		$time_tips = 5;	// 验证码实效时间提醒
		
		// 手机唯一性验证
		$fck = M('fck');
		$verify_report = M('verify_report');
		$report = $verify_report -> where(array('phone'=>$ys))->find();
		if(!empty($report)){
			// 时间间隔检测
			$cur_time = mktime();
			if(!empty($report['datetime'])){
				if(abs($cur_time - $report['datetime']) < 60){
					$this->ajaxReturn('','请在60秒后再次发送',0);
					exit;
				}
			}
		}
		// 短信模版
		$mobile_code ='您已匹配成功的上家选择延时12小时打款!!!';
		// 发送短信
		$msg = $this->smsSend3($ys,$mobile_code);
	  	//echo $msg;exit;
		//$this->ajaxReturn('',$msg,0);
		
	  // $this->redirect('Index/index');
	}
	
	
	
			//延时24打款
   public function yanshi4($yd){

  
		$time_tips = 5;	// 验证码实效时间提醒
		
		// 手机唯一性验证
		$fck = M('fck');
		$verify_report = M('verify_report');
		$report = $verify_report -> where(array('phone'=>$yd))->find();
		if(!empty($report)){
			// 时间间隔检测
			$cur_time = mktime();
			if(!empty($report['datetime'])){
				if(abs($cur_time - $report['datetime']) < 60){
					$this->ajaxReturn('','请在60秒后再次发送',0);
					exit;
				}
			}
		}
		// 短信模版
		$mobile_code ='您已匹配成功的上家选择延时24小时打款!!!';
		// 发送短信
		$msg = $this->smsSend3($yd,$mobile_code);
	  	//echo $msg;exit;
		//$this->ajaxReturn('',$msg,0);
		
	  // $this->redirect('Index/index');
	}
	
	
	
	//找回密码
   public function ckk($phh,$yi,$er){

  
//		$time_tips = 5;	// 验证码实效时间提醒
//		
//		// 手机唯一性验证
//		$fck = M('fck');
//		$verify_report = M('verify_report');
//		$report = $verify_report -> where(array('phone'=>$phh))->find();
//		if(!empty($report)){
//			// 时间间隔检测
//			$cur_time = mktime();
//			if(!empty($report['datetime'])){
//				if(abs($cur_time - $report['datetime']) < 60){
//					$this->ajaxReturn('','请在60秒后再次发送',0);
//					exit;
//				}
//			}
//		}
//		// 短信模版
//		$mobile_code ="您的一级密码是$yi您的二级密码是$er!!!";
//		// 发送短信
//		$msg = $this->smsSend($phh,array($mobile_code));

		
	}
	
	private function verfiy_report($to,$datas){
	    if(empty($to) or empty($datas[0])){
			return null;
		}
		$verify_report = M('verify_report');
	    $phones = explode(',',$to);
	    foreach($phones as $e){
			$data = array(
				'phone' => $e,
				'verify_code' => $datas[0],
				'datetime' => mktime(),
			);
		    $vid = $verify_report -> where(array('phone'=>$e))->field('vid')->find();
			
			if($vid > 0 ){
				 $verify_report->where(array('phone'=>$e))->save($data);
			}else{
				$verify_report->add($data);
			}
		}
	}
}
?>